<template>
  <div class="home">
    <!-- 头部 -->
    <van-nav-bar title="商品列表" />
    <!-- 头部导航 -->
    <ul class="nav">
      <li
        v-for="(item, index) in cateList"
        :key="index"
        @click="change(index, item._id)"
        :class="{ active: currentIndex == index }"
      >
        {{ item.title }}
      </li>
    </ul>
    <!-- 商品列表 -->
    <div v-if="filterList.length == 0">
       <van-empty description="空空如也" />
    </div>
    <van-card
      v-else
      v-for="item,index in filterList"
      :key="index"
      
      :price="item.price"
      :title="item.title"
      :thumb="item.pic"
    >
      <template #footer>
        <van-button color="#7232dd" round size="mini" @click="addCart(item)">+</van-button>
      </template>
    </van-card>
  </div>
</template>

<script>
import axios from "axios";
import { reactive, toRefs } from "vue";
import {useRouter} from 'vue-router'
import {useStore} from 'vuex'
export default {
  setup(props) {
    
    const data = reactive({
      cateList: [], //存放分类的数据
      list:[],//存放所有的数据
      filterList: [], //存放筛选过后的商品
      currentIndex: 0, //保存下标
    //   id: "", //保存id
    });
    // 调用useRouter
    const router = useRouter()
    console.log(router);
    const {push} = router
    // 调用useStore()
    // const store = useStore()
    // console.log(store);
    const {commit} = useStore()
    //  change(0,'59f1e1ada1da8b15d42234e9')
    //  请求  异步
    axios.get("cate.json").then((res) => {
      console.log(res);
      data.cateList = res.data.result;
    });
    // 请求商品列表 请求  异步
    axios.get("list.json").then((res) => {
      console.log(res);
      data.list = res.data.result
      change(0,'59f1e1ada1da8b15d42234e9')
    });
    // 点击nav的事件
    const change = (index, id) => {
      console.log(id);
      data.currentIndex = index;
    //   data.id = id;
      data.filterList = data.list.filter(item=>item.cid == id)
      console.log(data.filterList);

    };
    // 点击加入购物车事件
    const addCart = (item)=>{
        // 跳转到购物车页面
        push('/about')
        commit('addCart',item)


    }
    return { ...toRefs(data), change,addCart };
  },
  components: {
    // HelloWorld
  },
};
</script>
<style lang="scss" scoped>
.nav {
  display: flex;
  height: 45px;
  align-items: center;
  background: #44107d;
  color: #fff;

  li {
    flex: 1;
    text-align: center;
    height: 100%;
    line-height: 45px;
  }
  .active {
    background: #8d3ec5;
  }
}
</style>
